import argparse
from datetime import datetime
import time
import os
from sys import stdout


def _createarguments():
  """
  Function to create arguments from the main function
  """
  parser = argparse.ArgumentParser()
  parser.add_argument('-i', '--input', help="Trace file to convert", required=True)
  parser.add_argument('-o', '--output', help="File where to save the csv", required=True)
  parser.add_argument('-z', '--zero', help="convert node ids from 1-n to 0-n", action="store_true")
  return parser


def split_line(line):
  """
  Split the line of the trace, return array with:
  TimeStamp SenderNode ReceiverNode PacketSeqNo RSSI LQI
  """
  try:
    a = line.split(' ')
    return ['%s %s' % (a[0],a[1])] + a[2:]
  except IndexError, ie:
    return False


def date_to_uts(d):
  """
  Convert a date in the format 'YYYY/MM/DD HH:mm:ss'
  into an UTC string 
  """
  dt = datetime.strptime(d, '%Y/%m/%d %H:%M:%S')
  return str(long(time.mktime(dt.timetuple())))

def convert_id(id):
  """
  Convert a node id from the range 1-n to the range 0-n
  """
  new_id = int(id)
  return new_id-1
  

def main():
  parser = _createarguments()
  args = vars(parser.parse_args())
  if args['zero']:
    print "convert to node ids to 0-n representation"
  # open input file
  inp = open(args['input'], 'rU')
  # open output file
  out = open(args['output'],'w')
  # read
  r = 0
  for line in inp:
    arr = split_line(line.rstrip('\n'))
    if arr:
      arr[0] = date_to_uts(arr[0])
      arr[1] = str(convert_id(arr[1]))
      arr[2] = str(convert_id(arr[2]))
      s = "%s, %s, %s, %s, %s, %s"%(arr[0], arr[1], arr[2], arr[3], arr[4], arr[5])
      s = s + os.linesep
      out.write(s)
      r += 1
    if r%100 == 0:
      stdout.write(".")
      stdout.flush()
  stdout.write("\n")
  stdout.flush()
    

if __name__ == "__main__":
  main()
